import request from "request";
import { requestPromise, getCookieObject } from "../utils"
import { getBasicInfo } from "./getAcwSc";

export const getGigaAuth = async (
  email: string,
  password: string,
):Promise<string> => {
  const {
    acw_sc__v2,
    OCSESSID,
    'X-CSRF-TOKEN': X_CSRF_TOKEN,
  } = await getBasicInfo();
  const formData = {
    email,
    password,
    'X-CSRF-TOKEN': X_CSRF_TOKEN,
    'logged_redirect_url': '/',
  }
  const options: request.CoreOptions = {
    'method': 'POST',
    'timeout': 60 * 1000,
    formData,
    gzip: true,
    headers: {
      'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/538.36 (KHTML, like Gecko) Chrome/96.1.1638.34 Safari/538.36',
      'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
      'referer': 'https://www.gigab2b.com/index.php?route=account/login',
      'accept-encoding': 'gzip',
      'accept-language': 'n-US,en;q=0.9',
      'host': 'www.gigab2b.com',
      'cache-control': 'max-age=0',
      cookie: `acw_sc__v2=${acw_sc__v2}; OCSESSID=${OCSESSID}`,
    },
  };

  await requestPromise('https://www.gigab2b.com/index.php?route=account/login', options)
    .then(response => {
      const setCookie = response.headers['set-cookie'];
      if (!setCookie) {
        throw new Error('giga 请求头[set-cookie] 错误')
      }
      const loginFlag = getCookieObject(setCookie)['login_flag']
      if (loginFlag !== '1') {
        throw new Error('登录失败')
      }
    })

  return OCSESSID
}
